import socket
import threading
import os
import html as ht

def handle_client(c,addr):
    print(addr, "connected.")

    with c:
        request = c.recv(1024)
        
        headers = request.split(b"\r\n")
        file = headers[0].split()[1].decode()

        if file == "/":
            try:
                with open("index.html", "rb") as f:
                    content = f.read()
                response = b"HTTP/1.0 200 OK\r\n\r\n" + content
            except FileNotFoundError:
                response = b"HTTP/1.0 404 NOT FOUND\r\n\r\nFile not found!"+bytes("index.html", encoding = "utf8")

            c.sendall(response)
        elif file[0] == "/" and file[1] == "?":
            file = ht.unescape(file)
            print(file.replace("&","   ").replace('/?','').replace('+',' '))

            try:
                with open("success.html", "rb") as f:
                    content = f.read()
                response = b"HTTP/1.0 200 OK\r\n\r\n" + content
            except FileNotFoundError:
                response = b"HTTP/1.0 404 NOT FOUND\r\n\r\nFile not found!"+bytes(file, encoding = "utf8")
            c.sendall(response)

with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
    s.bind(("0.0.0.0",80))
    s.listen()

    while True:
        c,addr = s.accept()

        t = threading.Thread(target=handle_client, args=(c,addr))
        t.start()